package org.azj.dbOperatorComponent;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

public class SelectCommand extends DbQueryCommand 
{
	public String columnList;
	public String whereFilter;
	public String tableName;
	public List<OrderByPair> orderByList;
	public List<String> groupByList;
	public String havingFilter;
	public boolean distinct;
	
	@Override
	public PreparedStatement getStatement(Connection conn) throws Exception {
		if (columnList == null || tableName == null)
		{
			throw new Exception("columnList and tableName must be set before selceting");
		}
		
		String strDistinct = distinct == false? "" :" DISTINCT ";
		String tmp = String.format("SELECT %s %s FROM %s", strDistinct, columnList, tableName);
		
		if (whereFilter != null && whereFilter != "")
		{
			tmp = String.format("%s WHERE %s", tmp, whereFilter);
		}
		
		if (groupByList != null && groupByList.size() != 0)
		{
			String groupByString = "";
			for (String col : groupByList) {
				groupByString += col + ", ";
			}
			
			groupByString = groupByString.substring(0, groupByString.lastIndexOf(','));
			tmp = String.format("%s GROUP BY %s", tmp, groupByString);
			
			if (havingFilter != null && havingFilter != "")
			{
				tmp = String.format("%s HAVING %s", tmp, havingFilter);
			}
		}
		
		if (orderByList != null && orderByList.size() != 0)
		{
			String orderByString = "";
			for (OrderByPair pair : orderByList) {
				orderByString += pair.toString() + ", ";
			}
			
			orderByString = orderByString.substring(0, orderByString.lastIndexOf(','));
			tmp = String.format("%s ORDER BY %s", tmp, orderByString);
		}
		
		PreparedStatement preparedStatement = conn.prepareStatement(tmp);
		return preparedStatement;
	}
}
